//
//  PhoneLoginView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/6/18.
//

import SwiftUI
import ToastUI


struct PhoneLoginView: View {
    @StateObject private var weChatManager = WeChatManager.shared
    @State private var code = ""
    @State private var scene = "loginByCode"
    @State private var showToast = false
    @State private var isAgreed = false

    @StateObject var viewModel = LoginViewModel()
    @EnvironmentObject var appState:AppState
    var body: some View {
            VStack {
                ZStack {
                    Image("6528")
                        .resizable()
                        .frame(height: 194)
                    
                    Image("Kosspot")
                        .resizable()
                        .frame(width: 116,height: 52)
                    VStack {
                        Image("6711")
                            .resizable()
                            .frame(width: 143,height: 26)
                            .padding(.top,35)
                            .padding(.leading,-22)
                    }
                }
                //区号 手机号
                ZStack(alignment: .leading) {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(hex: "#F5F6FA"))
                        .frame(height: 44)
                    HStack {
                        Menu {
                            ForEach(viewModel.countryCodes, id: \.self) { item in
                                Button {
                                    let components = item.components(separatedBy: "：")
                                    if let countryCode = components.last?.trimmingCharacters(in: .whitespaces) {
                                        viewModel.selectedCode = countryCode
                                    }
                                } label: {
                                    Text(item)
                                }
                            }
                        } label: {
                            HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
                                Text(viewModel.selectedCode)
                                    .foregroundColor(.black)
                                Spacer().frame(width: 2)
                                Image("sanjiao")
                            })
                            .lineSpacing(0)
                        }
                        .frame(height: 44)
                        .padding(.leading, 18)
                        Spacer().frame(width: 8)
                        Capsule()
                            .frame(width: 1.3, height: 18)
                            .foregroundColor(Color (hex: "#B5B5B5"))

                        Spacer().frame(width: 8)
                        ZStack(alignment: .leading) {
                            if viewModel.username.isEmpty {
                                Text("请输入手机号码")
                                    .font(.system(size: 16))
                                    .foregroundColor(Color (hex: "#B5B5B5"))
                            }
                            TextField("", text: $viewModel.username)
                                .font(.system(size: 16))
                                .keyboardType(.phonePad)
                                .frame(height: 44)
                                .padding(.trailing, 18)
                                .foregroundColor(Color.black)
                                .autocapitalization(UITextAutocapitalizationType/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
                        }
                    }
                }
                .padding(.horizontal, 24)
                
                HStack (alignment: .center, content:{
                    ZStack(alignment:.leading) {
                        RoundedRectangle(cornerRadius: 8)
                            .fill(Color(hex: "#F5F6FA"))
                            .frame(height: 44)
                        if viewModel.code.isEmpty {
                            Text("请输入验证码")
                                .font(.system(size: 16))
                                .foregroundColor(Color (hex: "#B5B5B5"))
                                .padding(.leading, 18)
                        }
                        SecureField("", text: $viewModel.code)
                            .font(.system(size: 16))
                            .frame(height: 44)
                            .padding(.horizontal, 18)
                            .foregroundColor(Color.black)
                            .autocapitalization(UITextAutocapitalizationType.none)
                        
                    }
                    CountdownButton(mobile: $viewModel.username) {
                        viewModel.sendSMCcode(mobile: viewModel.username, scene: scene)
                    }
                })
                .frame(height: 44)
                .background(Color(hex: "#F5F6FA"))
                .cornerRadius(8.0)
                .padding(.horizontal, 24)
                .padding(.top, 16)
                HStack {
                    Button("注册"){
                        appState.navigateTo(.register)
                    }
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#D5D5D5"))
                    .padding(.trailing, 24)
                    .padding(.top, 16)
                    .frame(width: 100)
                    Spacer()
                    
                    Button("忘记密码?") {
                      appState.navigateTo(.resetPassword)
                    }
                    .font(.system(size: 14))
                    .foregroundColor(Color(hex: "#D5D5D5"))
                    .padding(.trailing, 24)
                    .padding(.top, 16)
                    .frame(width: 100)
                }
                
                HStack {
                    Spacer()
                    
                    Button(action: {
                        if viewModel.username.isEmpty {
                            viewModel.error = "请输入手机号码"
                            return
                        }
                        if viewModel.code.isEmpty {
                            viewModel.error = "请输入验证码"
                            return
                        }
                        if !isAgreed {
                            viewModel.error = "请同意用户服务协议"
                            return
                        }
                        viewModel.error = nil
                        viewModel.loginByCode(mobile: viewModel.username, code: viewModel.code)
                    }, label: {
                        HStack(alignment: .center, spacing: 0) {
                            Text("手机号登录/注册")
                                .font(.system(size: 16))
                                .foregroundColor(Color(hex: "#242424"))
                        }
                        .frame(maxWidth: .infinity, alignment: .center)
                    })
                    .padding()
                    .alert(isPresented: $viewModel.isLoginSuccess, content: {
                        Alert(title: Text("提示"), message: Text("登录成功!"), dismissButton: .default(Text("确认"), action: {
                            viewModel.isLoginSuccess = false
                            viewModel.error = nil
                            appState.navigateTo(.tabbar)
                        })
                        )
                    })
                    Spacer()
                }
                .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")])
                .cornerRadius(8.0)
                .padding([.trailing,.leading],24)
                .padding(.top, 16)
                
                Button("密码登录") {
                    appState.navigateTo(.passwordlogin)
                }.font(.system(size: 14))
                    .foregroundColor(Color(hex: "#D5D5D5"))
                    .padding(.top,16)
                Spacer()
                VStack {
                    if WXApi.isWXAppInstalled() {
                        HStack {
                            VStack {
                                Divider()
                                    .background(Color(hex: "#EEEEEE"))
                                    .padding(.leading,43)
                            }
                            Text("第三方登录")
                                .font(.system(size: 14))
                                .foregroundColor(Color(hex: "#999999"))
                            VStack {
                                Divider()
                                    .background(Color(hex: "#EEEEEE"))
                                    .padding(.trailing,43)
                            }
                        }
                        HStack {
                            Spacer()
                            Image("wx")
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 44,height: 44)
                                .onTapGesture {
                                    if !isAgreed {
                                        viewModel.error = "请同意用户服务协议"
                                        return
                                    }
                                    weChatManager.requestLogin()
                                }
                            Spacer()
                       /*     Button(action: {
                                //苹果登录
                            }) {
                            }
                            .background(
                                Image("apple")  // 使用Assets中的图片
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width: 44,height: 44)
                            )
                            Spacer()   */
                        }
                        .frame(height: 44)
                        .padding(.top,16)
                    }
                    HStack {
                        Toggle("", isOn: $isAgreed)
                            .toggleStyle(CustomToggleStyle())
                        Text("已阅读并同意")
                            .font(.system(size: 14))
                            .foregroundColor(Color(hex: "#888888"))
                        Spacer().frame(width: 0)
                        Button(action: {
                            //《用户服务协议》
                        }) {
                             Text("《用户服务协议》").foregroundColor(Color(hex: "#00E9DA"))
                                .font(.system(size: 14))
                                .foregroundColor(Color(hex: "#00E9DA"))
                                .padding(.vertical, 10)
                        }
                    }
                    .frame(height: 14)
                    .padding(.top,30)
                }
                .padding(.bottom,47)
            }
            .navigationBarHidden(true)
            .background(Color(hex: "#0A0A0A"))
            .edgesIgnoringSafeArea(.all)
            .dismissingKeyboard()
            .toast(isPresented: $showToast) {
                ShowMessageView(message: viewModel.error)
            }
            .onChange(of: viewModel.error) {
                newValue in
                if let errorMessage = newValue, !errorMessage.isEmpty {
                    showToast = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        showToast = false
                        viewModel.error = nil
                    }
                }
            }
            .onChange(of: weChatManager.loginSuccess) { newValue in
                if newValue.error == nil,
                   let accessToken = newValue.accessToken,
                   let openid = newValue.openid,
                   let unionid = newValue.unionid{
                    viewModel.oauthLogin(
                        oauthType: "wechat",
                        openid: openid,
                        accessToken: accessToken,
                        unionid: unionid
                    )
                }
            }
            .onChange(of: viewModel.isbindSuccess) { newValue in
                if newValue == true {
                    if viewModel.needBindMobile {
                        print("跳转到绑定手机页面")
                        if let openid = weChatManager.loginSuccess.openid,
                           let unionid = weChatManager.loginSuccess.unionid,
                           let accessToken = weChatManager.loginSuccess.accessToken{
                            appState.navigateTo(.bindPhoneNumber(accessToken:accessToken, openid: openid, unionid: unionid))
                        }
                        viewModel.isbindSuccess = false
                    }else {
                        appState.navigateTo(.tabbar)
                        viewModel.isbindSuccess = false
                    }
                }
            }
    }
}



       

#Preview {
    PhoneLoginView()
}

